# Importing Data
FRANCE <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Israel/France.xlsx")

# Checking the Imported Data
View(FRANCE)

# Creating Time Series Data
FRANCE_ts <- ts(FRANCE, start=c(2004,1), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
FRANCE_ts
sum(is.na(FRANCE_ts))
library(forecast)
FRANCE_ts <- tsclean(FRANCE_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(FRANCE_ts)
plot(aggregate(FRANCE_ts,FUN=mean))

# Decomposing
FRANCE_ts_decomp <- decompose(FRANCE_ts)
plot(FRANCE_ts_decomp)

# Testing for Stationarity
acf(FRANCE_ts, lag.max=20)
pacf(FRANCE_ts, lag.max=20)

# To see any seasonal effect
boxplot(FRANCE_ts~cycle(FRANCE_ts))

# To remove trend effect
FRANCE_ts_diff <- diff(FRANCE_ts)
plot(FRANCE_ts_diff)

# To remove variance effect
FRANCE_ts_log <- log(FRANCE_ts)
plot(FRANCE_ts_log)

# To remove both (Trend and Variance) effects
FRANCE_ts_both <- diff(log(FRANCE_ts))
plot(FRANCE_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(FRANCE_ts, lag.max=20)
acf(log(FRANCE_ts), lag.max=20)
acf(diff(FRANCE_ts), lag.max=20)
acf(diff(log(FRANCE_ts)), lag.max=20)
pacf(FRANCE_ts, lag.max=20)
pacf(log(FRANCE_ts), lag.max=20)
pacf(diff(FRANCE_ts), lag.max=20)
pacf(diff(log(FRANCE_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
FRANCE_ts_model <- auto.arima(FRANCE_ts)
FRANCE_ts_model
FRANCE_ts_model <- auto.arima(FRANCE_ts, ic="aic", trace = TRUE)
FRANCE_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(FRANCE_ts_model$resid)
acf(FRANCE_ts_model$residuals, main='ACF Residual')
pacf(FRANCE_ts_model$residuals, main='ACF Residual')
Box.test(FRANCE_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
FRANCE_ts_forecast <- forecast (FRANCE_ts_model, level=c(95), h=257)
plot(FRANCE_ts_forecast)
FRANCE_ts_forecast             


write.table(FRANCE_ts_forecast, file="France_TSA.csv", sep=",")
